package org.spider.spiderweb.controller;

import org.spider.api.domain.vo.FileVo;
import org.spider.api.domain.utilDomain.Result;
import org.spider.core.service.FileService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private FileService fileService;

    @GetMapping
    public Result fileList(){
        List<FileVo> list = fileService.list();
        return Result.getInstance(list);
    }

    @GetMapping("/download")
    public void downloadFile(@RequestParam("filename") String filename, HttpServletResponse resp) throws IOException {
        resp.addHeader("Content-Disposition", "attachment");
        resp.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        resp.setCharacterEncoding("UTF-8");
        fileService.download(filename,resp.getOutputStream());
    }

    @DeleteMapping("/delete")
    public Result delete(@RequestParam("filename") String[] filenames){
        boolean flag=true;
        if(filenames==null || filenames.length==0)
            return Result.getInstance(1,"未选中");
        for(String filename:filenames){
            if(!fileService.deleteFile(filename))
            {
                flag=false;
                break;
            }
        }
        return Result.getInstance(flag);
    }

}
